<template>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="编号" prop="id" />
    <el-table-column label="名称" prop="name" />
    <el-table-column label="单价">
      <template #default="scope">
        {{ scope.row.price }}
      </template>
    </el-table-column>
    <el-table-column label="数量">
      <template #default="scope">
        <el-button
          size="small"
          style="width: 2px"
          icon="el-icon-minus"
          :disabled="scope.row.number <= 0"
          @click="handleJian(scope.$index, scope.row)"
          >-</el-button
        >
        <span>{{ scope.row.number }}</span>
        <el-button
          size="small"
          style="width: 2px"
          icon="el-icon-plus"
          @click="handleJia(scope.$index, scope.row)"
          >+</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="小计">
      <template #default="scope">
        {{ scope.row.total }}
      </template>
    </el-table-column>
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="搜索" />
      </template>
      <template #default="scope">
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="allPrice">总价：{{ allTotal }}</div>
  <ShoppingChild />
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";

const search = ref("");
const tableData = ref([
  {
    id: "1",
    name: "电视",
    price: 1399,
    number: 1,
    total: 1399,
  },
  {
    id: "2",
    name: "平板",
    price: 2899,
    number: 1,
    total: 2899,
  },
  {
    id: "3",
    name: "手机",
    price: 5666,
    number: 1,
    total: 5666,
  },
  {
    id: "4",
    name: "鼠标",
    price: 99,
    number: 1,
    total: 99,
  },
]);
//搜索
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
);
// 总价
const allTotal = computed(() =>
  filterTableData.value.reduce((acc, item) => acc + item.total, 0)
);
// 删除
const handleDelete = (index, row) => {
  const i = tableData.value.findIndex((item) => item.id === row.id);
  if (i !== -1) {
    tableData.value.splice(i, 1);
  }
};
//加号
const handleJia = (index, row) => {
  const item = tableData.value[index];
  item.number++;
  item.total = item.price * item.number;
};
// 减号
const handleJian = (index, row) => {
  const item = tableData.value[index];
  if (item.number > 0) {
    item.number--;
    item.total = item.price * item.number;
  }
};
</script>
